import service from '@/utils/request';
import { tansParams, blobValidate } from '@/utils/index';
import { Message } from '@arco-design/web-vue';
import { saveAs } from 'file-saver';

const download = (
  url: any,
  params: any,
  filename: any,
  cb: (arg0: boolean) => void
) => {
  if (cb) {
    cb(true);
  }
  return service
    .request({
      url,
      data: params,
      method: 'post',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      transformRequest: [
        (transParams: any) => {
          return tansParams(transParams);
        },
      ],
    })
    .then(async (data: any) => {
      const isLogin = await blobValidate(data);
      if (isLogin) {
        const blob = new Blob([data]);
        saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        if (rspObj.code !== 200) {
          Message.error(rspObj.msg);
        }
      }
      if (cb) {
        cb(false);
      }
    });
};
export const operlog = (params: any, cb: any) => {
  download(
    'monitor/operlog/export',
    params,
    `operlog_${new Date().getTime()}.xlsx`,
    cb
  );
};
export const logininfor = (params: any, cb: any) => {
  download(
    'monitor/logininfor/export',
    params,
    `logininfor_${new Date().getTime()}.xlsx`,
    cb
  );
};

export const dictType = (params: any, cb: any) => {
  download(
    'system/dict/type/export',
    params,
    `dict_type_${new Date().getTime()}.xlsx`,
    cb
  );
};
export const dictData = (params: any, cb: any) => {
  download(
    'system/dict/data/export',
    params,
    `dict_data_${new Date().getTime()}.xlsx`,
    cb
  );
};

export const post = (params: any, cb: any) => {
  download(
    'system/post/export',
    params,
    `post_${new Date().getTime()}.xlsx`,
    cb
  );
};

export const role = (params: any, cb: any) => {
  download(
    'system/role/export',
    params,
    `role_${new Date().getTime()}.xlsx`,
    cb
  );
};

export const user = (params: any, cb: any) => {
  download(
    'system/user/export',
    params,
    `user_${new Date().getTime()}.xlsx`,
    cb
  );
};
export const userImportTemplate = (params?: any, cb?: any) => {
  download(
    'system/user/importTemplate',
    params,
    `user_import_template_${new Date().getTime()}.xlsx`,
    cb
  );
};
export const patientImportTemplate = (params?: any, cb?: any) => {
  cb(true);
  saveAs(
    '../../src/assets/template/patient_import.xlsx',
    `patient_import_template${new Date().getTime()}.xlsx`
  );
  cb(false);
};
export default null;
